<template>
  <div>
    <a-modal
      title="人员导入"
      :visible="visible"
      :confirm-loading="confirmLoading"
      :width="600"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-form-model
        ref="ruleForm"
        :model="formData"
        :rules="rules"
        layout="horizontal"
        labelAlign="left"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
      >
        <a-form-model-item label="人员数据表格" prop="excelList">
          <a-upload
            :file-list="formData.excelList"
            :remove="excelHandleRemove"
            :before-upload="excelBeforeUpload"
            accept=".xlsx,.xls"
          >
            <a-button> <a-icon type="upload" /> 选择文件</a-button>
          </a-upload>
          <p class="desc">
            录入说明:<br>
            1.第一行的红色字段是必填项，黑色字段是选填项<br>
            2.录入的部门、工种信息需提前添加好才能导入成功，否则导入后部门为默认部门<br>
            3.最后一列的[图片文件名]录入时必须跟导入的人脸图片名称一致，后缀名[.jpg]不能缺少<br>
            4.工号录入时不能有重复的<br>
            <a-button type="link" @click="onDown" style="padding:0;">下载导入模板</a-button>
          </p>
        </a-form-model-item>
        <a-form-model-item label="头像 " prop="photoList">
          <a-upload
            :file-list="formData.photoList"
            :remove="photoHandleRemove"
            :before-upload="photoBeforeUpload"
            accept=".zip,.rar"
          >
            <a-button> <a-icon type="upload" /> 选择文件</a-button>
          </a-upload>
          <p class="desc">上传说明：图片名必须和表格中的图片文件名一致（类型是压缩包）</p>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>
    <script>
import { importFile } from '@/utils/importFile'
import { exportFile } from '@/utils/exportFile'
export default {
  data() {
    return {
      pkey: '',
      visible: false,
      confirmLoading: false,
      formData: {
        excelList: [],
        photoList: [],
      },
      rules: {
        excelList: [{ required: true, message: '请上传人员数据表格', trigger: 'change' }],
        photoList: [{ required: true, message: '请上传头像 ', trigger: 'change' }],
      },
    }
  },
  methods: {
    add() {
      this.visible = true
    },
    async onDown() {
      const res = await exportFile('api/manager/person/v1/import/template',{},'人员导入模板.xlsx')
    },
    handleOk() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          this.confirmLoading = true
          const formData = new FormData()
          formData.append('excel', this.formData.excelList[0])
          formData.append('Photo', this.formData.photoList[0])

          const res = await importFile('api/manager/person/v1/import', formData)
          const { statusCode, errors } = res.data
          this.confirmLoading = false
          if (statusCode == 200) {
            this.visible = false
            this.$message.success('导入成功！')
            this.$emit('saveSuccess')
            this.$parent.getTableData()
          } else {
            this.$message.error(JSON.stringify(errors))
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
    excelHandleRemove(file) {
      const index = this.formData.excelList.indexOf(file)
      const newFileList = this.formData.excelList.slice()
      newFileList.splice(index, 1)
      this.formData.excelList = newFileList
    },
    excelBeforeUpload(file) {
      // 判断文件类型
      const isExcel =
        file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
        file.type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.error('仅允许 xls 或  xlsx 文件类型!')
        return
      }
      this.formData.excelList = [file]
      return false
    },
    photoHandleRemove(file) {
      const index = this.formData.photoList.indexOf(file)
      const newFileList = this.formData.photoList.slice()
      newFileList.splice(index, 1)
      this.formData.photoList = newFileList
    },
    photoBeforeUpload(file) {
      // 判断文件类型
      const isZipOrRar = file.type === 'application/x-zip-compressed' || this.isZipOrRar(file.name)
      if (!isZipOrRar) {
        this.$message.error('仅允许 zip 或  rar 文件类型!')
        return
      }
      this.formData.photoList = [file]
      return false
    },
    isZipOrRar(fileName) {
      const extension = fileName.slice(fileName.lastIndexOf('.') + 1).toLowerCase();
      return extension === 'zip' || extension === 'rar';
    }
  },
}
</script>
        
<style lang="less" scoped>
.desc {
  font-size: 14px;
  color: #999999;
  line-height: 20px;
}
</style>